package com.duo.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duo.dto.*;
import com.duo.entity.Category;
import com.duo.entity.Dish;
import com.duo.entity.DishFlavor;
import com.duo.enums.errorcode.DishCode;
import com.duo.exception.BaseException;
import com.duo.mapper.CategoryMapper;
import com.duo.mapper.DishFlavorMapper;
import com.duo.mapper.DishMapper;
import com.duo.result.PageResult;
import com.duo.service.DishService;
import com.duo.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Xrx
 * @Description:
 * @CreateTime: 2023/7/6 18:42
 */
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
        implements DishService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    /**
     * 新增菜品
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        checkDishName(dishDTO.getName());
        // 设置菜品口味
        this.save(dish);
        Long dishId = dish.getId();
        List<DishFlavorDTO> tmp = dishDTO.getFlavors();
        List<DishFlavor> flavors = new ArrayList<>();
        if (CollUtil.isNotEmpty(tmp)) {
            tmp.forEach(flavor -> {
                DishFlavor dishFlavor = new DishFlavor();
                BeanUtils.copyProperties(flavor, dishFlavor);
                dishFlavor.setDishId(dishId);
                flavors.add(dishFlavor);
            });
            flavors.forEach(flavor -> {
                dishFlavorMapper.insert(flavor);
            });
        }
        log.info("新增菜品成功");
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        Integer current = dishPageQueryDTO.getCurrent();
        Integer pageSize = dishPageQueryDTO.getSize();
        String name = dishPageQueryDTO.getName();
        String description = dishPageQueryDTO.getDescription();
        BigDecimal price = dishPageQueryDTO.getPrice();
        Page<Dish> dishPage = new Page<>(current, pageSize);
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(Dish::getCategoryId, dishPageQueryDTO.getCategoryId());
        if (StrUtil.isNotBlank(name)) {
            dishWrapper.like(Dish::getName, name);
        }
        if (StrUtil.isNotBlank(description)) {
            dishWrapper.like(Dish::getDescription, description);
        }
        if (ObjectUtil.isNotEmpty(price)) {
            dishWrapper.eq(Dish::getPrice, price);
        }
        if (ObjectUtil.isNotNull(dishPageQueryDTO.getStatus())) {
            dishWrapper.eq(Dish::getStatus, dishPageQueryDTO.getStatus());
        }
        Page<Dish> result = this.page(dishPage, dishWrapper);
        List<Dish> records = result.getRecords();
        List<DishVO> dishVOS = new ArrayList<>();
        records.forEach(dish -> { 
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            dishVO.setDishId(dish.getId());
            LambdaQueryWrapper<DishFlavor> flavorWrapper = new LambdaQueryWrapper<>();
            flavorWrapper.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(flavorWrapper);
            dishVO.setFlavors(dishFlavors);
            dishVOS.add(dishVO);
        });
        PageResult pageResult = new PageResult();
        pageResult.setTotal(result.getTotal());
        pageResult.setRecords(dishVOS);
        return pageResult;
    }

    /**
     * 菜品删除
     * @param dishDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(DishDeleteDTO dishDto) {
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(Dish::getId, dishDto.getDishId());
        dishWrapper.eq(Dish::getStatus, 1);
        Dish dish = this.getOne(dishWrapper);
        if (ObjectUtil.isNull(dish)) {
            log.error("菜品删除失败，原因：菜品不存在");
            throw new BaseException(DishCode.DISH_NO_FOUND_ERROR);
        }
        baseMapper.deleteById(dishDto.getDishId());
        log.info("菜品删除成功");
    }

    /**
     * 菜品批量删除
     * @param dishList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<DishDeleteDTO> dishList) {
        dishList.forEach(this::delete);
        log.info("菜品批量删除成功");
    }

    /**
     * 菜品更新
     * @param dishDTO
     */
    @Override
    public void update(DishUpdateDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        this.updateById(dish);
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(Dish::getId, dishDTO.getId());
        dish = this.getOne(dishWrapper);
        if (ObjectUtil.isNull(dish)) {
            log.error("菜品不存在");
            throw new BaseException(DishCode.DISH_NO_FOUND_ERROR);
        }
        // 设置菜品口味
        List<DishFlavorDTO> dishDTOFlavors = dishDTO.getFlavors();
        if (CollUtil.isNotEmpty(dishDTOFlavors)) {
            Long dishId = dish.getId();
            LambdaQueryWrapper<DishFlavor> flavorWrapper = new LambdaQueryWrapper<>();
            flavorWrapper.eq(DishFlavor::getDishId, dishId);
            dishFlavorMapper.delete(flavorWrapper);
            List<DishFlavor> flavors = new ArrayList<>();
            dishDTOFlavors.forEach(flavor -> {
                DishFlavor dishFlavor = new DishFlavor();
                BeanUtils.copyProperties(flavor, dishFlavor);
                dishFlavor.setDishId(dishId);
                flavors.add(dishFlavor);
            });
            flavors.forEach(flavor -> {
                dishFlavorMapper.insert(flavor);
            });
        }
        log.info("菜品更新成功");
    }


    private void checkDishName(String name) {
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(Dish::getName, name);
        dishWrapper.eq(Dish::getStatus, 1);
        Dish dish = this.getOne(dishWrapper);
        if (ObjectUtil.isNotNull(dish)) {
            log.error("菜品新增失败，原因：菜品名称已存在");
            throw new BaseException(DishCode.DISH_NAME_EXIST_ERROR);
        }
    }

    private Long checkCategory(String categoryName) {
        LambdaQueryWrapper<Category> categoryWrapper = new LambdaQueryWrapper<>();
        categoryWrapper.eq(Category::getName, categoryName);
        categoryWrapper.eq(Category::getType, 1);
        Category category = categoryMapper.selectOne(categoryWrapper);
        if (ObjectUtil.isNull(category)) {
            log.error("菜品新增失败，原因：菜品分类不存在");
            throw new BaseException(DishCode.DISH_NO_CATEGORY_ERROR);
        }
        return category.getId();
    }

}
